package com.ifonly.common.typeconverter.impl;

import com.ifonly.common.typeconverter.Converter;
import com.ifonly.common.typeconverter.TypeConversionException;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-17 20:01
 * @since JDK 1.6
 */
public class LongConverter implements Converter<Long> {
    @Override
    public Long convert(Object value) {
        if (value == null) {
            return null;
        }

        if (value.getClass() == Long.class) {
            return (Long) value;
        }
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        if (value instanceof Boolean) {
            return (Boolean) value ? Long.valueOf(1L) : Long.valueOf(0L);
        }

        try {
            String stringValue = value.toString().trim();
            return Long.valueOf(stringValue);
        } catch (NumberFormatException e) {
            throw new TypeConversionException(value, e);
        }
    }
}
